<?php
class Model_Review extends Zend_Db_Table_Abstract
{
   	protected $_table;

    public function getTable()
    {
        if (null === $this->_table) {            
            require_once APPLICATION_PATH . '/models/DbTable/Review.php';
            $this->_table = new Model_DbTable_Review;
        }
        return $this->_table;
    }
   
    public function save(array $data)
    {
    	if(isset($data['id'])){
    		$id = $data['id'];
    	}else{
    		$id = 0;
    	}
    		
        $table  = $this->getTable();
        $fields = $table->info(Zend_Db_Table_Abstract::COLS);        
        foreach ($data as $field => $value) {
            if (!in_array($field, $fields)) {
                unset($data[$field]);                
            }            
        }

        if($id == 0){
        	return $table->insert($data);
        }else{
        	$where = $table->getAdapter()->quoteInto('id = ?', $id);
        	return $table->update($data, $where);
        }
    }
   
    public function fetchEntries()
    {       
        return $this->getTable()->fetchAll('1')->toArray();
    }
    public function getByAssignmentId($id)
    {
        $table = $this->getTable();
        $select = $table->select()->where('assignment_id = ?', $id);    
        return $table->fetchRow($select);
    }
	public function getByPaperId($paper_id){
		$table = $this->getTable();		 			
		$db = $table->getAdapter();			
		$select = $db->select()->from(array('r' => 'reviews'), 
		array('id', 'comment', 'conf_comment', 'theory_grade', 'practice_grade', 'overview_grade', 'grade', 'date_reviewed'))
							->join(array('a' => 'assignments'), 'a.id = r.assignment_id', array('date_assigned', 'date_downloaded'))
                            ->join(array('p' => 'participants'), 'p.id = a.reviewer_id', array('first_name', 'last_name'))
							->where('a.paper_id = ?', $paper_id);
		$stmt = $select->query();		
      return $stmt->fetchAll();
	}
    public function getReviewsCount($assignment_id){
        $table = $this->getTable();		 					        
        $select = $table->select();
        $select->from($table, array('count' => 'COUNT(id)'))->where('assignment_id = ?', $assignment_id);           
		$res = $table->fetchRow($select);        
        $c = $res->toArray();
    	return $c['count'];
    } 	
    public function fetchEntry($id)
    {
        $table = $this->getTable();
        $select = $table->select()->where('id = ?', $id);    
        return $table->fetchRow($select);
    } 	
   
}
